package vip.hsq168.plugin.flutter_immersion_bar


import android.util.Log
import com.gyf.immersionbar.ImmersionBar
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar


class FlutterImmersionBarPlugin : MethodCallHandler {
    private var immersionBar: ImmersionBar? = null

    companion object {
        @JvmStatic
        fun registerWith(registrar: Registrar) {
            val channel = MethodChannel(registrar.messenger(), "vip.hsq168.plugin.flutter_immersion_bar")
            var plugin = FlutterImmersionBarPlugin();
            channel.setMethodCallHandler(plugin);
//            registrar.addViewDestroyListener {view->
//                plugin.onDestroy(registrar);
//                return@addViewDestroyListener false;
//            };
            plugin.onCreate(registrar);
        }
    }

    private var funMap = mapOf(
            ::statusBarAlpha to fun(call: MethodCall): Array<Any> {
                return arrayOf(call.arguments<Double>().toFloat())
            },
            ::statusBarColor to { call: MethodCall -> arrayOf(call.arguments<Int>()) },
            ::statusBarDarkFont to { call: MethodCall ->
                var args = (call.arguments as ArrayList<*>);
                arrayOf(args[0], (args[1] as Double).toFloat())
            }
    )

    private fun onDestroy(registrar: Registrar) {
        //ImmersionBar.with(registrar.activity()).destroy();
    }

    fun onCreate(registrar: Registrar) {
        immersionBar = ImmersionBar.with(registrar.activity());
        immersionBar?.init()

    }


    override fun onMethodCall(call: MethodCall, result: Result) {
        var hasHandler = false;
        for (funKey in funMap.keys) {
            if (funKey.name.equals(call.method)) {
                hasHandler = true;
                try {
                    var args = funMap[funKey]?.invoke(call);
                    funKey.call(*args!!);
                    Log.d("ImmersionBarPlugin", "${funKey.name}:$args" );
                    result.success(true)
                } catch (e: Exception) {
                    Log.e("ImmersionBarPlugin", "onMethodCall", e);
                    result.success(false)
                }
            }
        }
        if (!hasHandler) {
            result.notImplemented()
        }
    }

    fun statusBarAlpha(statusAlpha: Float) {
        immersionBar?.statusBarAlpha(statusAlpha)?.init();
    }


    fun statusBarColor(color: Int) {
        immersionBar?.statusBarColor(color)?.init();
    }

    fun statusBarDarkFont(isDarkFont: Boolean, statusAlpha: Float) {
        immersionBar?.statusBarDarkFont(isDarkFont, statusAlpha)?.init();
    }
}
